//
//  AlibabaModule.m
//  lovebaby
//
//  Created by 陈星华 on 2020/3/14.
//  Copyright © 2020年 Facebook. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "AlibabaModule.h"

#define SuccessCode 0
#define FailCode -1

@implementation AlibabaModule

+ (instancetype) sharedInstance
{
  static AlibabaModule *instance = nil;
  if (!instance) {
    instance = [[AlibabaModule alloc] init];
  }
  return instance;
}

// 初始化
- (void)asyncInit: (RCTResponseSenderBlock)callback{
  // 百川平台基础SDK初始化，加载并初始化各个业务能力插件
  [[AlibcTradeSDK sharedInstance] setDebugLogOpen:YES];//开发阶段打开日志开关，方便排查错误信息
  [[AlibcTradeSDK sharedInstance] setIsvVersion:@"2.2.2"];
  [[AlibcTradeSDK sharedInstance] setIsvAppName:@"lovebaby"];
  
  [[AlibcTradeSDK sharedInstance] asyncInitWithSuccess:^{
    TLOG_INFO(@"百川SDK初始化成功");
    NSDictionary *ret = @{@"code": @(1), @"msg": @"初始化成功"};
    callback(@[@SuccessCode,ret]);
  } failure:^(NSError *error) {
    TLOG_INFO(@"百川SDK初始化失败");
    NSLog(@"%@", [error localizedDescription]);
    NSDictionary *ret = @{@"code": @(error.code), @"msg":  [error localizedDescription]};
    callback(@[@FailCode,ret]);
  }];
  
}

// 登陆
- (void)showLogin: (RCTResponseSenderBlock)callback{
  
  [[ALBBSDK sharedInstance]setAuthOption:NormalAuth];
  [[ALBBSDK sharedInstance]auth:[UIApplication sharedApplication].delegate.window.rootViewController            successCallback:^(ALBBSession *session){
    ALBBUser *s = [session getUser];
    NSDictionary *ret = @{@"nick": s.nick, @"avatarUrl":s.avatarUrl, @"openId":s.openId};
    callback(@[@SuccessCode, ret]);
  }
                failureCallback:^(ALBBSession *session, NSError *error){
                  NSDictionary *ret = @{@"code": @(error.code), @"msg":error.description};
                  callback(@[@FailCode,ret]);
                }];
  
}

// 是否已经登陆
- (void)isLogin: (RCTResponseSenderBlock)callback{
  bool isLogin = [[ALBBSession sharedInstance] isLogin];
  callback(@[@SuccessCode, [NSNumber numberWithBool: isLogin]]);
}

// 获取用户数据
- (void)getUserInfo: (RCTResponseSenderBlock)callback{
  bool isLogin = [[ALBBSession sharedInstance] isLogin];
  if(isLogin){
    ALBBUser *s = [[ALBBSession sharedInstance] getUser];
    NSDictionary *ret = @{@"nick": s.nick, @"avatarUrl":s.avatarUrl, @"openId":s.openId};
    callback(@[@SuccessCode, ret]);
    
  }else{
    callback(@[@FailCode,[NSNull null]]);
  }
}

// 退出登陆
- (void)logout: (RCTResponseSenderBlock)callback{
  [[ALBBSDK sharedInstance] logout];
  callback(@[@SuccessCode,[NSNull null]]);
}

- (void)showPage: (NSDictionary *)param callback: (RCTResponseSenderBlock)callback{
    RCTLog(@"not implement=======================00000");
  NSString *type = param[@"type"];
  NSDictionary *payload = (NSDictionary *)param[@"payload"];
  
  if ([type isEqualToString:@"detail"]) {
    id<AlibcTradePage>  page = [AlibcTradePageFactory itemDetailPage:(NSString *)payload[@"itemid"]];
    [self openByBizCode:page param:param callback:callback];
    
  }else if([type isEqualToString:@"url"]){
    RCTLog(@"not implement=======================1111");
    [self openByUrl:param url:(NSString *)payload[@"url"] callback:callback];
    
  }else if([type isEqualToString:@"shop"]){
    id<AlibcTradePage>  page = [AlibcTradePageFactory shopPage:(NSString *)payload[@"shopid"]];
    [self openByBizCode:page param:param callback:callback];
    
  }else if([type isEqualToString:@"orders"]){
    id<AlibcTradePage>  page = [AlibcTradePageFactory myOrdersPage:(NSInteger)payload[@"orderStatus"] isAllOrder:(BOOL)payload[@"allOrder"]];
    [self openByBizCode:page param:param callback:callback];
    
  }else if([type isEqualToString:@"addCard"]){
    id<AlibcTradePage>  page = [AlibcTradePageFactory addCartPage:(NSString *)payload[@"itemid"]];
    [self openByBizCode:page param:param callback:callback];
    
  }else if([type isEqualToString:@"mycard"]){
    id<AlibcTradePage>  page = [AlibcTradePageFactory myCartsPage];
    [self openByBizCode:page param:param callback:callback];
    
  }else{
    RCTLog(@"not implement");
    return;
  }
}

-(void)openByBizCode :(id<AlibcTradePage>)page param:(NSDictionary *)param callback:(RCTResponseSenderBlock)callback{
  
  NSDictionary *payload = (NSDictionary *)param[@"payload"];
  NSString *_bizCode = @"";
  if ((NSString *)payload[@"BizCodeStr"] != nil ) {
    _bizCode =payload[@"BizCodeStr"];
  }
  
  [[AlibcTradeSDK sharedInstance].tradeService
                   openByBizCode: _bizCode
                   page:page
                   webView:NULL
                   parentController:[UIApplication sharedApplication].delegate.window.rootViewController
                   showParams:[self dealShowParam:param]
                   taoKeParams:[self dealTaokeParams:param]
                   trackParam:[self dealExParams:param]
                   tradeProcessSuccessCallback:^(AlibcTradeResult * _Nullable result) {
                     NSDictionary *ret = @{@"msg": @"成功！"};
                      callback(@[@SuccessCode, ret]);
                   }
                   tradeProcessFailedCallback:^(NSError * _Nullable error) {
                     NSDictionary *ret = @{@"msg": @"失败！"};
                     callback(@[@FailCode, ret]);
                   }];
}

-(void)openByUrl:(NSDictionary *)param url:(NSString *)url callback: (RCTResponseSenderBlock)callback{
  
  [[AlibcTradeSDK sharedInstance].tradeService
     openByUrl:url
     identity:@"trade" //当前是固定传入
     webView: NULL
     parentController:[UIApplication sharedApplication].delegate.window.rootViewController
     showParams:[self dealShowParam:param]
     taoKeParams:[self dealTaokeParams:param]
     trackParam:[self dealExParams:param]
     tradeProcessSuccessCallback:^(AlibcTradeResult * _Nullable result) {
       NSDictionary *ret = @{@"msg": @"成功！"};
       callback(@[@SuccessCode, ret]);
     }
     tradeProcessFailedCallback:^(NSError * _Nullable error) {
       NSDictionary *ret = @{@"msg": @"失败！"};
       callback(@[@FailCode, ret]);
     }];
}

-(AlibcTradeShowParams *)dealShowParam:(NSDictionary *)param{
  NSDictionary *payload = (NSDictionary *)param[@"payload"];
  AlibcTradeShowParams* showParams = [[AlibcTradeShowParams alloc] init];
  
  NSString *_OpenType = (NSString *)payload[@"OpenType"];
  NSString *_clientType = (NSString *)payload[@"clientType"];
//  NSString *_BACK_URL =(NSString *)payload[@"BACK_URL"];
  NSString *_AlibcFailModeType = (NSString *)payload[@"AlibcFailModeType"];
  
  // OpenType ：Native表示唤端，Auto表示不做设置
  if ([_OpenType isEqualToString:@"Auto"]) {
    showParams.openType = AlibcOpenTypeAuto;
  }
  if ([_OpenType isEqualToString:@"Native"]) {
      showParams.openType = AlibcOpenTypeNative;
  }
  
  // clientType ：taobao---唤起淘宝客户端；tmall ---唤起天猫客户端
  if ([_clientType isEqualToString:@"taobao"] || [_clientType isEqualToString:@"tmall"] ) {
    showParams.linkKey = _clientType;
  }
  
  showParams.isNeedCustomNativeFailMode = true;
//  showParams.isNeedPush = true;
  
  
  if ([_AlibcFailModeType isEqualToString:@"AlibcNativeFailModeNONE"]) {
    showParams.nativeFailMode =AlibcNativeFailModeNone;
  }
  if ([_AlibcFailModeType isEqualToString:@"AlibcNativeFailModeJumpBROWER"]) {
    showParams.nativeFailMode =AlibcNativeFailModeJumpH5;
  }
  if ([_AlibcFailModeType isEqualToString:@"AlibcNativeFailModeJumpDOWNLOAD"]) {
    showParams.nativeFailMode =AlibcNativeFailModeJumpDownloadPage;
  }
  if ([_AlibcFailModeType isEqualToString:@"AlibcNativeFailModeJumpH5"]) {
    showParams.nativeFailMode =AlibcNativeFailModeJumpH5;
  }
  
  return showParams;
}

- (AlibcTradeTaokeParams *)dealTaokeParams:(NSDictionary *)param{
  NSDictionary *payload = (NSDictionary *)param[@"payload"];
  AlibcTradeTaokeParams *taokeParams = [[AlibcTradeTaokeParams alloc] init];
  
  NSString *pid = @"";
  NSString *adzoneid =  @"";
  NSString *tkkey = @"";
  NSString *sellerId =  @"";

  if ((NSString *)payload[@"Pid"] != nil ) {
    pid =payload[@"Pid"];
  }
  
  if ((NSString *)payload[@"Adzoneid"] != nil) {
    adzoneid =payload[@"Adzoneid"];
  }
  
  if ((NSString *)payload[@"taokeAppkey"] != nil ) {
    tkkey =payload[@"taokeAppkey"];
  }
  
  if ((NSString *)payload[@"sellerId"] != nil ) {
    sellerId =payload[@"sellerId"];
  }
  
  taokeParams.pid = pid;
  taokeParams.adzoneId = adzoneid;
  taokeParams.extParams = @{
                            @"taokeAppkey":tkkey,
                            @"sellerId":sellerId
                            };
  
  return taokeParams;
}


-(NSDictionary *)dealExParams:(NSDictionary*) param{
  NSString *isvcode = @"";
  NSDictionary *payload = (NSDictionary *)param[@"payload"];
  
  if ((NSString *)payload[@"isvcode"] != nil ) {
    isvcode =payload[@"isvcode"];
  }
  NSDictionary *trackParam=@{@"isv_code":isvcode};
  return trackParam;
}



@end


